<template>
  <div class="login">
    <nav-bar>
      <template v-slot:center>
        <span style="font-size: 0.16rem; color: #fff">用户登录</span>
      </template>
    </nav-bar>
    <van-image width="100" height="100" src="https://img01.yzcdn.cn/vant/cat.jpeg" class="img-icon" round />
    <van-form @submit="onSubmit">
      <van-field
        v-model="email"
        type="email"
        name="email"
        label="电子邮箱"
        placeholder="电子邮箱"
        :rules="[{ required: true, message: '请填写电子邮箱' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <router-link to="/register" class="link">没有账号？去注册</router-link>

      <div style="margin: 16px">
        <van-button round block native-type="submit" class="btn">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { userLogin } from 'network/user.js'
import { reactive, toRefs } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router'
export default {
  name: 'Login',
  setup(props) {
    //获取路由实例
    const route = useRoute()
    const router = useRouter()
    // Vuex 实例
    const store = useStore()
    // 用户信息
    let userInfo = reactive({
      email: '',
      password: ''
    })
    function onSubmit(value) {
      userLogin(value).then(res => {
        // 将token保存在本地
        localStorage.setItem('token', res.access_token)
        Toast.success('登录成功!')
        // 清空用户信息
        userInfo.email = ''
        userInfo.password = ''
        // 将用户登录状态修改为成功
        store.commit('login/SETISLOGIN', true)
        store.dispatch('cart/updateCart')
        // 判断用户登录成功后该跳转到哪里
        if (route.query.redirect) {
          router.push(route.query.redirect)
        } else {
          router.push('/home')
        }
      })
    }
    return {
      onSubmit,
      ...toRefs(userInfo)
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  width: 100vw;
  .img-icon {
    margin: 0.2rem auto;
    display: block;
  }
  .btn {
    background: #42b983 !important;
    color: white;
  }
  .link {
    padding: 0.2rem 0 0 0.2rem;
    display: block;
    color: #42b983;
  }
}
</style>